﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Management;
using System.IO;
using System.Text;

namespace Janus.NorthwindDemo2007
{
    static class Program
    {
        static string _pathLicense = Application.StartupPath + "\\License.bin";
        public static string _key = "newoppo123456789";
        public static string _iv = "12345678";
        public static string _padMode = "PKCS7";
        public static string _opMode = "CBC";
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);
            try
            {
                ValidateLicense();
            }
            catch (Exception ex)
            {
                if (MessageBox.Show(ex.Message + "\n Bạn muốn đăng ký sử dụng phần mềm?", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    FrmLicense frm = new FrmLicense();
                    if (frm.ShowDialog() != DialogResult.OK) return;
                    //if (frm.DialogResult != DialogResult.OK) 
                }
                else
                    return;
            }
            try
            {
                ResetConnectionString();
            }
            catch (Exception e)
            {
                return;
            }
            NorthwindApp.Initialize();
        }
        private static void ValidateLicense()
        {
            if (File.Exists(_pathLicense))
            {
                StreamReader reader = new StreamReader(_pathLicense);
                string result = reader.ReadLine();
                string kq = RC2.DecryptString(result, _key, _iv, _padMode, _opMode);
                string[] tmp = kq.Split(';');
                DTO.License license = new DTO.License();
                license.CompanyName = tmp[0];
                license.ExpiryDate = Convert.ToInt32(tmp[1]);
                license.Modules = tmp[2];
                license.NumUsers = Convert.ToInt32(tmp[3]);
                license.SerialNumber = tmp[4];
                license.Key = tmp[5];
                //license.SerialCPU = tmp[6];
                license.SerialCPU = GetProcessorId();
                reader.Close();


                string param = license.CompanyName + license.SerialNumber + license.NumUsers.ToString() + license.Modules + license.ExpiryDate.ToString() + license.SerialCPU;


                string temp = RC2.EncryptString(param, _key, _iv, _padMode, _opMode);
                string key = Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(temp)));
                if (key == license.Key)
                {
                    int now = Convert.ToInt32(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00"));
                    object dt = DateTime.Today;
                    if (dt != null && dt is DateTime)
                    {
                        now = Convert.ToInt32(((DateTime)dt).Year.ToString() + ((DateTime)dt).Month.ToString("00") + ((DateTime)dt).Day.ToString("00"));
                    }
                    if (now > license.ExpiryDate)
                    {
                        throw new Exception("Your license is expired!");
                    }
                    else
                    {

                    }
                }
                else
                {
                    throw new Exception("Application have not license!");
                }

            }
            else
            {
                throw new Exception("Application have not license!");
            }
        }
        public static string GetProcessorId()
        {
            string strCPU = "";
            string Key = "Win32_Processor";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
            try
            {
                foreach (ManagementObject share in searcher.Get())
                {
                    if (share.Properties.Count <= 0)
                    {
                        return "";
                    }
                    foreach (PropertyData PC in share.Properties)
                    {
                        if (PC.Name == "ProcessorId")
                        {
                            strCPU = Convert.ToString(PC.Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //radLabel_Err.Text = ex.Message;
            }
            return strCPU;
        }

        private static void ResetConnectionString()
        {

            string DBDir = GetDBDirectory();
            if (DBDir.Length == 0)
            {
                System.Windows.Forms.OpenFileDialog openFiledlg = new OpenFileDialog();
                openFiledlg.Filter = "Database files|*.mdb|All files|*.*";
                openFiledlg.FileName = "JanusNorthWindDemo.mdb";
                if (openFiledlg.ShowDialog() == DialogResult.OK)
                {
                    DBDir = openFiledlg.FileName;
                }
            }
            else
            {
                DBDir += "\\JanusNorthWindDemo.mdb";
            }
            System.IO.FileInfo fInfo = new System.IO.FileInfo(DBDir);
            if (!fInfo.Exists)
            {
                MessageBox.Show("File '" + fInfo.FullName + "' does not exist.", NorthwindApp.MessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw new Exception();
            }
            Properties.Settings.Default["NorthwindDataConnectionString"] = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DBDir + ";";
            //Properties.Settings.Default["NorthwindDataConnectionString"] = "Provider = SQLOLEDB;Data Source=.;Initial Catalog=JanusNorthWindDemo;User ID=sa;Password=123456;Connect Timeout=500";

        }
        private static string GetDBDirectory()
        {

            System.IO.DirectoryInfo currentDirectory = new System.IO.DirectoryInfo(System.Windows.Forms.Application.ExecutablePath).Parent;
            while (currentDirectory != null)
            {

                System.IO.DirectoryInfo[] childDirectories = currentDirectory.GetDirectories();

                foreach (System.IO.DirectoryInfo childDir in childDirectories)
                {

                    if (childDir.Name == "Data")
                    {
                        return childDir.FullName;
                    }
                }
                currentDirectory = currentDirectory.Parent;
            }
            return "";
        }


    }
}